package org.redis.cluster.support;

import java.util.concurrent.atomic.AtomicInteger;

import org.redis.cluster.RedisCluster;
import org.redis.cluster.config.ServerConfig;
import org.redis.cluster.event.AbstractSessionEventListener;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.transport.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionController extends AbstractSessionEventListener implements Plugin {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private final AtomicInteger currentConnectionCounter=new AtomicInteger();
	private final static AtomicInteger connectionRefusedCounter=new AtomicInteger();
	
	private ServerConfig config;
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.config=redisCluster.getConfigManager().getServerConfig();
	}
	
	@Override
	public void destroy() {
	}

	protected void doSessionCreatedProcess(Session session) {
		if(currentConnectionCounter.incrementAndGet()>config.getConnection()) {
			if(logger.isInfoEnabled()) {
				logger.info("连接被拒绝  - {}",session.getRemoteAddress());
			}
			
			connectionRefusedCounter.incrementAndGet();
			session.close();
		}
	}

	protected void doSessionClosedProcess(Session session) {
		currentConnectionCounter.decrementAndGet();
	}
	
	public static int getRefusedConnectionCount() {
		return connectionRefusedCounter.get();
	}
}